package com.jvyou.thread.test04;

import java.util.Random;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/7/31 16:31
 * @Description
 */
public class RedEnvelope implements Runnable {

    /*剩余红包的个数*/
    private int num = 3;
    /*剩余红包的金额*/
    private int money = 100;

    private final Integer MIN_MONEY = 1;

    @Override
    public void run() {
        synchronized (this) {
            if (num <= 0) {
                System.out.println(Thread.currentThread().getName() + "没有抢到");
            } else if (num == 1) {
                System.out.println(Thread.currentThread().getName() + "抢到了" + money + "元");
                num--;
            } else {
                Random random = new Random();
                // 必须预留足够的金额给下面的抽奖
                int effectiveAmount = money - MIN_MONEY * (num - 1);
                int m = random.nextInt(effectiveAmount);
                if (m < MIN_MONEY) {
                    m = MIN_MONEY;
                }
                System.out.println(Thread.currentThread().getName() + "抢到了" + m + "元");
                money -= m;
                num--;
            }
        }
    }

    public static void main(String[] args) {
        RedEnvelope redEnvelope = new RedEnvelope();
        for (int i = 0; i < 5; i++) {
            new Thread(redEnvelope, "学生" + i).start();
        }
    }
}
